<template>
	<div class="login-container">
        <!-- 导航栏 -->
        <TridentNavBar>
            <template #default>密码登录</template>
			<template #right>
				<i class="icon iconfont icon-shouye1" @click="$router.push({path: '/'})"></i>
			</template>
        </TridentNavBar>

        <!-- logo -->
		<div class="logo-wapper" @click="goto('/')">
			<van-image :src="loginImage" class="logo" />
			<div class='text'>想聊几块钱，就聊几块呗！</div>
		</div>
		
        <!-- 表单 -->
		<div class="login-box">
			<!-- 基础表单校验 -->
			<van-form @submit="handlerLogin">
                <van-cell-group inset>
                    <!-- 手机号 -->
					<van-field
						v-model="formData.mobile"
						:label-width="labelWidth"
						type="number"
						name="手机号"
						label="手机号"
						placeholder="请输入手机号"
						left-icon="phone"
						maxlength="11"
						:rules="[
							{ required: true, message: '请输入手机号' },
							{ validator, message: '请输入正确格式的手机号' }
						]"
					/>
					
					<!-- 验证码 -->
					<van-field
						v-model="formData.code"
						type="number"
						name="验证码"
						label="验证码"
						:label-width="labelWidth"
						placeholder="请输入验证码"
						left-icon="lock"
						maxlength="6"
						:rules="[{ required: true, message: '请输入验证码' }]"
					>
						<template #button>
							<van-button
								class="code-btn"
								size="small"
								:disabled="!rightMobile"
								:color="!rightMobile ? 'gray' : '#27BA9B'"
								type="primary"
								@click="sendCode"
							>
								{{time ? '剩余' + time + 's' : '发送验证码'}}
							</van-button>
						</template>
					</van-field>
                </van-cell-group>

                <!-- 登录按钮 -->
                <div style="margin: 16px">
                    <van-button
                        type="primary"
                        native-type="submit"
                        round
                        block
                        color="#27BA9B"
                    >
                        登&nbsp;&nbsp;录
                    </van-button>
                </div>
			</van-form>
			
			<div class="footer-wapper">
				<div @click="goto('/passwordLogin')">密码登录</div>
				<div @click="goto('/register')" style="font-size: 18px;color: #E83915;">还没有账户</div>
				<div @click="goto('/forgotPassword')">找回密码</div>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, computed} from "vue"
import { useUserStore } from '@/store/modules/user'
import { reqLoginSendCodeAPI } from "@/apis/user"
import loginImage from '@/assets/images/logo.png'
import { showSuccessToast } from 'vant'
import {useRouter, useRoute} from 'vue-router'

// ----------------- 定义全局变量开始 -----------------
// 用户存储
const userStore = useUserStore()

// 输入框标签宽度
const labelWidth = ref('50px')

// 路由
const route = useRoute() 

// 路由器
const router = useRouter() 

// 提交数据
const formData = reactive({
	mobile: '',
	code: ''
})
// ----------------- 定义全局变量结束 -----------------



// ---------------- 发送验证码功能开始 ----------------
const rightMobile = computed(() => {
	// 手机正则
	const pattern = /^1[3|5|7|8|9]\d{9}$/
	return pattern.test(formData.mobile)
})

// 过期时间
const time = ref(0)

// 发送验证码
const sendCode = async () => {
	if(time.value == 0) {
		// 请求验证码接口
		await reqLoginSendCodeAPI(formData.mobile || '')
		
		showSuccessToast('发送成功')
		
		time.value = 60
		const intervalId = setInterval(() => {
			time.value--
			if(time.value == 0) {
				clearInterval(intervalId)
			}
		}, 1000)
	}
}
// ---------------- 发送验证码功能结束 ----------------



// ----------------- 处理登录功能开始 -----------------
const validator = (value: string) => /^1[3|5|7|8|9]\d{9}$/.test(value)
// 登录
const handlerLogin = async () => {
	await userStore.login(formData, 2)

	showSuccessToast('欢迎回来')
	setTimeout(() => {
		const redirectUrl = decodeURIComponent(route.query.redirect as never)
		
		// 登录成功后，跳转url不为空并且不等于退出页，则跳转至跳转url，否则跳转至首页
		// 必须跳转至我的页面的redirectUrl
		const unRedirectUrls = [
			'/userSet',
			'/passwordLogin',
			'/messageLogin',
			'/forgotPassword',
			'/register',
		]

		if (redirectUrl == "undefined" || redirectUrl == "" || redirectUrl == 'null'|| unRedirectUrls.includes(redirectUrl)) {
			router.push({path: '/'})
		} else {
			router.push({path: redirectUrl})
		}
	}, 1000)
}
// ----------------- 处理登录功能结束 -----------------



// ----------------- 处理跳转功能开始 -----------------
const goto = (url: string) => {
	router.push({path: url})
}
// ----------------- 处理跳转功能结束 -----------------
</script>

<style scoped lang="scss">
.login-container {
    background: ghostwhite;
    height: calc(100vh - 47px);
}

.logo-wapper {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	margin-top: 47px;
	margin-bottom: 60px;
    padding-top: 40px;
	.logo {
		width: 175px;
		height: 75px;
	}
	.text {
		font-size: 13px;
		color: #666;
	}
}
.footer-wapper {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	margin-top: 10px;
	color: #909399;
}
.login-box {
	position: relative;
	top: 5px;
	margin: 0 10px;
	.login-btn {
		background-color: #27BA9B;
		color: white;
		width: 100%;
		border-radius: 23px;
	}
	.code-box {
		display: flex;
		justify-content: space-between;
		.code-btn {
			background-color: darkgray;
			width: 90px;
			height: 35px;
			line-height: 35px;
			color: #fff; 
			font-size: 12px;
			margin-left: 80px;
			&.active {
				background-color: #27BA9B;
			}
		}
	}
}
</style>
